#!/bin/bash
echo "===== 开始网络调优 ====="
# 错误处理机制
trap 'echo "脚本被终止，正在清理..."' INT TERM
# 权限检查
if [[ $EUID -ne 0 ]]; then
    echo "请以root用户身份运行此脚本"
    exit 1
fi
# 记录开始时间
start_time=$(date +%s.%N)
# 收集初始网络指标
echo "收集初始网络状态..."
initial_network_usage=$(ifstat eth0 | awk '{print $3}')
# 网络调优参数
TCP_WINDOW_SCALING=1
TCP_KEEPALIVE_TIME=60
IP_FORWARD_PROTO=2
# 应用sysctl调优
sysctl -p <<-EOF
net.ipv4.tcp_window_scaling=$TCP_WINDOW_SCALING
net.ipv4.tcp_keepalive_time=$TCP_KEEPALIVE_TIME
net.ip_forward_proto=$IP_FORWARD_PROTO
EOF
# 加载tuned网络优化配置
echo "应用tuned网络优化..."
tuned -p network-latency
# 收集调优后的网络指标
final_network_usage=$(ifstat eth0 | awk '{print $3}')
# 计算优化效果
 improvement=$(( ($initial_network_usage - $final_network_usage) * 100 / $initial_network_usage ))
# 结构化输出
echo "===== 调优结果 ====="
echo "初始网络带宽: ${initial_network_usage}KB/s"
echo "调优后网络带宽: ${final_network_usage}KB/s"
echo "优化提升率: ${improvement}%"
# 性能指标结构化输出
end_time=$(date +%s.%N)
duration=$(echo "$end_time - $start_time" | bc)
echo "===== 网络性能指标 ====="
echo '{
    "total_time": "'$duration'",
    "initial_usage": "'$initial_network_usage'",
    "final_usage": "'$final_network_usage'",
    "improvement_rate": "'$improvement'"
}'
# 记录日志
echo "网络调优完成，结果已输出" >> net_tuning.log
exit 0